<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Orders;
use App\Models\OrdersLog;
use App\Models\Ordertotals;
use App\Models\GoodsOrder;
use App\Models\MerchantOrder;
use App\Models\CouterOrder;
use Dingo\Api\Http\Request;
use App\Models\FreightWay;
use Illuminate\Support\Facades\DB;
use App\Services\Machine\OutGoods;
use App\Events\WeChatNoticeEvent;
use Illuminate\Support\Facades\Redis;
use App\Services\Mqtt\Publishs;
use Illuminate\Support\Facades\Log;
class OrderCatrController extends Controller
{
    protected $orders;
    protected $orderslog;
    protected $orderstotals;
    protected $goodsOrder;
    protected $merchantOrder;
    protected $couterOrder;
    protected $freightWay;

    public function __construct(Orders $orders,OrdersLog $orderslog,Ordertotals $orderstotals, GoodsOrder $goodsOrder, MerchantOrder $merchantOrder, CouterOrder $couterOrder, FreightWay $freightWay)
    {
        $this->orders = $orders;
        $this->orderslog = $orderslog;
        $this->orderstotals = $orderstotals;
        $this->goodsOrder = $goodsOrder;
        $this->merchantOrder = $merchantOrder;
        $this->couterOrder = $couterOrder;
        $this->freightWay = $freightWay;
    }
    /**
     * 确认订单
     * @param Request $request
     */
    public function confirmOrder(Request $request)
    {
        $machineId = $request->machineId;
        $goodsId = $request->goodsId;
        $order = [];
        $result = $this->freightWay
            ->select('freight_ways.machine_id', 'freight_ways.price', 'goods.*')
            ->leftJoin('goods', 'goods.id', '=', 'freight_ways.goods_id')
            ->where('goods.id', $goodsId)
            ->where('machine_id', $machineId)
            ->first();
    }

    public function payOrdercatr(Request $request)
    {
        $userId = $request->userId; // 用户ID
        $merchantId = $request->merchantId; // 商家id
        $operationId = $request->operationId; // 运维id
        $machineId = $request->machineId; // 设备ID
        $source = $request->source; // 1 微信 2支付宝
        $openid = $request->openid; // openid
        $goodsinfo = $request->goods;// 购物车信息
        if(!$userId){
            $msg = '缺少用户ID';
            return $this->fail($msg);
        }
        if(!$merchantId){
            $msg = '缺少商家id';
            return $this->fail($msg);
        }
        if(is_null($operationId)){
            $msg = '缺少运维id';
            return $this->fail($msg);
        }
        if(!$machineId){
            $msg = '缺少设备ID';
            return $this->fail($msg);
        }
        if(!$source){
            $msg = '缺少支付方式';
            return $this->fail($msg);
        }
        if(!$openid){
            $msg = '缺少用户openid';
            return $this->fail($msg);
        }
        if(!$goodsinfo){
            $msg = '缺少购物车信息';
            return $this->fail($msg);
        }
        //if($userId && $merchantId && !is_null($operationId) && $machineId && $source && $openid && $goodsinfo){
            $payOrder = json_decode($goodsinfo,1);
            $goodids = '';
            $mainboradnos = '';
            foreach($payOrder as $k=>$v){
                $goodids .= $v['goods_id'].',';
                $mainboradnos .= $v['No'].',';
                $goodprices[] = $v['count'] * $v['price'];
                $goodcount[] = $v['count'];
            }
            $goodids = trim($goodids,',');  
            $mainboradnos = trim($mainboradnos,',');
            $goodnums = array_sum($goodcount);
            $totalPrice = 0;
            // 获取设备编号
            $machineinfo = DB::table('machines')->where('id','=',$machineId)->select('imei')->first();
            // 获取主订单号
            $orderSnp = $this->OrderSnp($machineId);
            $zorderdata = [
                    'ordertotalid' => $orderSnp,//主订单ID
                    'machineid' => $machineId,//设备Id
                    'userid' => $userId,//用户ID
                    'merchant_id' => $merchantId,//商户ID
                    'operation_id' => $operationId,//运维ID
                    'amounts' => $source,//数量                
                    'goodsids' => $goodids,//商品ids(多商品)
                    'mainboradnos' => $mainboradnos,//货道ID
                    'goods_total_amount' => '',//商品总价
                    'created_at' => date('Y-m-d H:i:s',time()),
                    'updated_at' => date('Y-m-d H:i:s',time())
                ];
            Log::info('payOrdercatrce123', [$zorderdata]);
            $zorderId = Ordertotals::insertGetId($zorderdata);
            $totalPrice = 0;
            $insertTab = 0;
            DB::beginTransaction();
            static $zsnpsn = 1;
            foreach( $payOrder as $k => $v){
                $goodsId = $v['goods_id'];
                $mainboradNo = $v['No'];
                if ($machineId && $mainboradNo && $source && $userId) {
                    $goods = $this->freightWay
                            ->select('freight_ways.price','freight_ways.buying_price','machines.imei','machines.name')
                            ->leftJoin('machines', 'machines.id', '=', 'freight_ways.machine_id')
                            ->where('freight_ways.machine_id', $machineId)
                            ->where('freight_ways.No', $mainboradNo)
                            ->first();
                    $price = !is_null($goods) ? $goods->price : 0; 
                    $totalPrice += $price * $v['count'];
                    if($price){
                        for($i=0; $i<$v['count']; $i++){
                            // 获取子订单号
                            $data = array(
                                'user_id' => $userId,
                                'goodsid' => $goodsId,
                                'couter_id' => $machineId,
                                'machines_imel' => !is_null($goods) ? $goods->imei : '',
                                'machines_name' => !is_null($goods) ? $goods->name : '',
                                'freightway_id' => $mainboradNo,
                                'goods_total_price' => $price,//商品单价
                                'order_total_price' => $price,
                                'order_buying_price' => $goods->buying_price,//进货价
                                'payment' => $source,
                                'refund_status' => 0,
                                'order_status' => 0,
                                'ordersnp' => $orderSnp,
                                'ordersn' => $orderSnp.'_'.$zsnpsn,
                                'payment_time' => date('Y-m-d H:i:s',time()),
                                'created_at' => date('Y-m-d H:i:s',time()),
                                'updated_at' => date('Y-m-d H:i:s',time())
                            );
                            $zsnpsn++;
                            $orderId = $this->orders->insertGetId($data);
                            $merchantOrder = DB::table('merchant_orders')
                                ->insert([
                                    'merchant_id' => $merchantId,
                                    'operation_id' => $operationId,
                                    'order_id' => $orderId,
                                    'created_at' => date('Y-m-d H:i:s',time()),
                                    'updated_at' => date('Y-m-d H:i:s',time())
                                ]);
                            $goodsOrder = DB::table('goods_orders')
                                ->insert([
                                    'order_id' => $orderId,
                                    'goods_id' => $goodsId,
                                    'created_at' => date('Y-m-d H:i:s',time()),
                                    'updated_at' => date('Y-m-d H:i:s',time())
                                ]);
                            $couterOrder = DB::table('couter_orders')
                                ->insert([
                                    'order_id' => $orderId,
                                    'couter_id' => $machineId,
                                    'created_at' => date('Y-m-d H:i:s',time()),
                                    'updated_at' => date('Y-m-d H:i:s',time())
                                ]);
                            if($merchantOrder && $goodsOrder && $couterOrder){
                                $insertTab++;
                            }
                        }
                    }else{
                        //金额异常
                        return $this->payfail('金额异常');
                    }
                }     
            }
            Ordertotals::where('id', '=', $zorderId)->update(['goods_total_amount' => $totalPrice]);
            if($orderId && $insertTab == $goodnums){
                DB::commit();//成功，提交事务
                if($totalPrice){
                    $pay = new \App\Http\Controllers\Api\PayOrdercatrController;
                    $bankType = $source == 1 ? 'WX' : 'ALIPAY';
                    $merchantInfo = DB::table('users_codes')->select('customerNum','shopNum','shopAccess','shopSecret')->where('merchant_id',$merchantId)->first();
                    if(!$merchantInfo){
                        return $this->shopfail('商户不存在');
                    }
                    if($openid){
                        $payOrder = $pay->createDLBPay($orderSnp,$bankType,$totalPrice,$openid,$merchantInfo);    
                        $res = json_encode($payOrder['data']);                  
                        switch ($payOrder['result']) {
                            case 'fail'://失败
                                //订单操作日志
                                Log::info('orderlog',[$payOrder]);
                                $this->orderslog->create(['key'=>'订单失败', 'value' => json_encode($res), 'ordersn' => $payOrder['data']['requestNum']]);
                                return $this->fail('订单支付创建失败',$payOrder);
                                break;
                            case 'error'://异常
                                //订单操作日志
                                Log::info('orderlog',[$payOrder]);
                                $this->orderslog->create(['key'=>'订单异常', 'value' => json_encode($res), 'ordersn' => $payOrder['data']['requestNum']]);
                                return $this->fail('服务器繁忙，支付调用失败',$payOrder);
                                break;
                            default:
                                //$res = ['orderNum'=>$payOrder['$payOrder'], 'errorMsg'=>$payOrder['errorMsg']];
                                $this->orderslog->create(['key'=>'订单成功', 'value' => json_encode($res), 'ordersn' => $payOrder['data']['requestNum']]);
                                return $this->success($payOrder);
                                break;
                        }  
                    }
                }
            }else{
                DB::rollBack();//失败，回滚事务
                return $this->fail();
            }
        //}
        //return $this->fail();
    }

    // 支付后，修改订单状态
    public function orderStatuscatr(Request $request){
        $orderSn = $request->orderSn;
        if($orderSn){
            $merchantInfo = DB::table('orders')
                ->leftJoin('merchant_orders','merchant_orders.order_id','=','orders.id')
                ->leftJoin('users_codes','users_codes.merchant_id','=','merchant_orders.merchant_id')
                ->select('users_codes.customerNum','users_codes.shopNum','users_codes.shopAccess','users_codes.shopSecret')
                ->where('orders.ordersn',$orderSn)
                ->first();
            $pay = new \App\Http\Controllers\Api\PayOrdercatrController;
            $result = $pay->payStatus($orderSn,$merchantInfo);      
            return $this->success($result);
        }
        return $this->fail();
    }
    // 生成主订单SN
    protected function OrderSnp($machineId){
        $machineId = str_pad($machineId,5,"0",STR_PAD_LEFT);
        $orderSn = '';
        $orderSn = 'Z_HRC_';
        $orderSn .= date('YmdHis');
        $orderSn .= mt_rand(10000, 99999).$machineId;
        return $orderSn;
    }
    public function callbackOrdercatr(Request $request)
    {
        $orderSnp = $request->requestNum; //主订单号
        $orderAmount = $request->orderAmount;
        $orderStatus = $request->status;
        $outGoods = new OutGoods();
        if($orderSnp){
                $ordertotal = $this->orderstotals->where('ordertotalid',$orderSnp)->first();
                if($ordertotal){
                    if($orderStatus == 'SUCCESS' && $orderAmount == $ordertotal->goods_total_amount){
                        //根据著订单号查询相应子订单
                        $orders = $this->orders->where('ordersnp',$ordertotal->ordertotalid)->get();
                        $freightway_ids = [];
                        foreach($orders as $k=>$v){
                            Log::info('callbackordernum', [1]);
                            $machines = DB::table('machines')->where('imei',$v->machines_imel)->first();
                            $machinesFlag = 0;
                            if($machines){
                                $machinesFlag = DB::table('freight_ways')
                                    ->where('machine_id',$machines->id)
                                    ->where('No',$v->freightway_id)
                                    ->decrement('stock');
                                $freightWayInfo = DB::table('freight_ways')
                                    ->where('machine_id',$machines->id)
                                    ->where('No',$v->freightway_id)
                                    ->first();
                            }
                            $orderFlag = $v->update(['order_status'=>1, 'payment_time' => date('Y-m-d H:i:s',time())]);
                            $manager = DB::table('manager_third_auths')
                                ->leftJoin('merchant_orders','merchant_orders.merchant_id','=','manager_third_auths.manager_id')
                                ->where('merchant_orders.order_id',$v->id)
                                ->first();
                            $outGoods->outGoods($v->ordersn,$v->freightway_id,$v->machines_imel);
                            $freightway_ids = $v->freightway_id;
                        }
                        $freightWayStr = implode(';', array_unique($freightway_ids));
                        if($manager){
                            if($manager->push_type){
                                $push = json_decode($manager->push_type,1);
                                $ispush = $push['buy']['val'];
                                if($ispush){
                                    // 推送
                                    //购物车订单中加入总订单号 总金额
                                    $msg = '售卖通知 -- 单号：'.$ordertotal->ordertotalid.' 总金额：'.$orderAmount.' 货道号：'.$freightWayStr;
                                    event(new WeChatNoticeEvent($manager->wx_open_id, $msg));
                                }
                            }
                        }
                        Log::info('callbackorderwxreturnok', ['ok']);                 
                        return "ok";
                    }
                }
            return $this->success();
        }
        return $this->fail();
    }
    public function shipmentStatus(Request $request)
    {
        $machines_imel = $request->machines_imel; // 设备号IMEL
        $status = $request->status; // 1.出货成功，3.出货超时，4.设备故障
        $ordersn = $request->ordersn;
        if($status && $ordersn && $machines_imel){
            $data = $this->orders
                ->where('ordersn',$ordersn)
                ->where('machines_imel',$machines_imel)
                ->update(['order_status'=>$status]);
            $result = $this->orders
                ->where('ordersn',$ordersn)
                ->select('ordersn','machines_imel','order_status')
                ->orderBy('id','desc')->first();
                if($status == 4 || $status == 3){
                    $refundOrderSn = $this->refundOrderSn();
                    $orders = $this->orders->where('ordersn',$ordersn)->first();
                    if($orders) {
                        $data = array(
                            'goodsid' => $orders->goodsid,
                            'userid' => $orders->user_id,
                            'ordersn' => $ordersn,
                            'refund_ordersn' => $refundOrderSn,
                            'return_num' => 1,
                            'created_at' => date('Y-m-d H:i:s', time()),
                            'updated_at' => date('Y-m-d H:i:s', time()),
                            'return_content' => $status == 4 ? '设备故障' : '出货超时',
                        );
                        $refundsId =  DB::table('refunds')->insertGetId($data);
                        if($refundsId){
                            $merchantInfo = DB::table('orders')
                                ->leftJoin('merchant_orders','merchant_orders.order_id','=','orders.id')
                                ->leftJoin('users_codes','users_codes.merchant_id','=','merchant_orders.merchant_id')
                                ->select('users_codes.customerNum','users_codes.shopNum','users_codes.shopAccess','users_codes.shopSecret')
                                ->where('orders.ordersn',$ordersn)
                                ->first();
    
                            $pay = new \App\Http\Controllers\Api\PayOrdercatrController;
                            $result = $pay->refundDLBPay($ordersn,$refundOrderSn,$merchantInfo);
    
                            if('success' == $result['result']){
                                $this->orders
                                    ->where('ordersn',$ordersn)
                                    ->update(['refund_status' => 2]);
                            }
                            return $this->success($result);
                        }
                    }
                }
        }
        return $this->success($result);
    }
    public function getOrderStatus(Request $request)
    {
        $ordersn = $request->ordersn;
        if($ordersn){
            $result = $this->orders
                ->where('ordersn',$ordersn)
                ->select('ordersn','order_status')
                ->orderBy('id','desc')->first();
            if($result){
                if($result->order_status == 2 ){
                    $result->status = '已支付已出货';
                }else if($result->order_status == 3 ){
                    $result->status = '已超时';
                }else if($result->order_status == 4) {
                    $result->status = '设备故障';
                }else if($result->order_status == 1){
                        $result->status = '已支付待出货';
                }else{
                    $result->status = '待支付';
                }
            }
            return $this->success($result);
        }

        return $this->fail();
    }

    //生成退款
    public function refundOrder(Request $request){
        //https://openapi.duolabao.com/v3/order/refund
        $orderid = $request->id;
        $orders = $this->orders->find($orderid);
            if(in_array(optional($orders)->order_status,[3,4]) && optional($orders)->refund_status == 0){
                // 判断订单是否自动退款还是手动退款
            if(in_array(optional($orders)->freight_status,[3,4,5,6])){
                $machine = DB::table('machines')->where('imei',$orders->machines_imel)->where('is_auto_refund',0)->first(); 
            }else{
                $machine = DB::table('machines')->where('imei',$orders->machines_imel)->first();
            }
            if($machine){
                if($orders){
                    $refundOrderSn = $this->refundOrderSn();
                    $data = array(
                        'goodsid' => $orders->goodsid,
                        'userid' => $orders->user_id,
                        'ordersn' => $orders->ordersn,
                        'refund_ordersn' => $refundOrderSn,
                        'return_num' => 1,
                        'created_at' => date('Y-m-d H:i:s', time()),
                        'updated_at' => date('Y-m-d H:i:s', time()),
                        'return_content' => $orders->order_status == 3 ? '超时退款' : '设备故障退款'
                    );
                    $refundsId = DB::table('refunds')->insertGetId($data);
                    if($refundsId){
                        $merchantInfo = DB::table('merchant_orders')
                            ->leftJoin('users_codes', 'users_codes.merchant_id', '=', 'merchant_orders.merchant_id')
                            ->select('users_codes.customerNum', 'users_codes.shopNum', 'users_codes.shopAccess', 'users_codes.shopSecret')
                            ->where('order_id', $orders->id)
                            ->first();
                        $pay = new \App\Http\Controllers\Api\PayOrdercatrController;

                        $index_char = substr($orders->ordersn, 0, 1);
                        $ordersn = $index_char == 'Z' ? substr($orders->ordersn,0,-2) : $orders->ordersn;
                        $refundPartAmount = $orders->order_total_price;
                        $result = $pay->refundDLBPay($ordersn, $refundOrderSn, $merchantInfo, $refundPartAmount);
                        Log::info('refundresult', [$result]);
                        if('success' == $result['result']){
                            $manager = DB::table('manager_third_auths')
                                ->leftJoin('merchant_orders','merchant_orders.merchant_id','=','manager_third_auths.manager_id')
                                ->where('merchant_orders.order_id',$orders->id)
                                ->first();
                            if($manager){
                                if($manager->push_type){
                                    $push = json_decode($manager->push_type,1);
                                    $ispush = $push['lack']['val'];
                                    if($ispush){
                                        // 推送
                                        //退款通知订单中加入总订单号 总金额
                                        $msg = '退款通知 -- 单号：'.$ordersn.' 金额：'.$refundPartAmount;
                                        event(new WeChatNoticeEvent($manager->wx_open_id, $msg));
                                    }
                                }
                            }
                            $this->model->where('ordersn', $orders->ordersn)->update(['refund_status' => 2]);
                            return $this->success();
                        }
                        return $this->expirss();
                    }                 
                } 
                return $this->expirss();
            }  
        } 
        
        return $this->expirss();
    }

    // 生成订单SN
    protected function refundOrderSn()
    {
        $orderSn = '';
        $orderSn = 'HRCTK_';
        $orderSn .= date('YmdHis');
        $orderSn .= mt_rand(1, 99999);
        return $orderSn;
    }


}
